<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { Order } from '#/api/business/order/model';

import { Page, useVbenDrawer } from '@vben/common-ui';

import { message, Popconfirm, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  cancelOrder,
  orderExport,
  orderList,
  orderRefund,
} from '#/api/business/order';

import { columns, querySchema } from './data';
import OrderStatusModal from './order-status-drawer.vue';

const formOptions: VbenFormProps = {
  commonConfig: {
    componentProps: {
      allowClear: true,
      class: 'w-full',
    },
  },
  schema: querySchema(),
  showCollapseButton: false,
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

const gridOptions: VxeGridProps = {
  columns,
  height: 'auto',
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await orderList({
          pageNo: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  id: 'order-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [StatusDrawer, statusDrawerApi] = useVbenDrawer({
  connectedComponent: OrderStatusModal,
});

/**
 * 修改订单预约状态
 */
async function handleUpdateOrderStatus(record: Order) {
  statusDrawerApi.setData({ id: record.id }).open();
}

/**
 * 取消订单
 */
async function handleCancelOrder(row: Order) {
  await cancelOrder(row.id!);
  message.success('取消订单成功');
  await tableApi.query();
}

/**
 * 订单退款
 */
async function handleOrderRefund(row: Order) {
  await orderRefund(row.id!);
  message.success('订单退款成功');
  await tableApi.query();
}

/**
 * 导出订单
 */
async function openExportModal() {
  const pageNo = tableApi.grid.getCurrentPage();
  const pageSize = tableApi.grid.getPageSize();

  const params: any = {
    pageNo,
    pageSize,
    ...tableApi.formApi.form.values,
  };

  try {
    const blob = await orderExport(params);

    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `订单_${Date.now()}.xlsx`;
    document.body.append(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(url);

    message.success('导出成功');
  } catch {
    message.error('导出失败');
  }
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="订单管理">
      <template #toolbar-tools>
        <a-button
          type="primary"
          @click="openExportModal"
          v-access:code="['order:export']"
        >
          导出
        </a-button>
      </template>
      <template #action="{ row }">
        <Space>
          <!-- 修改预约状态 -->
          <ghost-button
            v-if="row.orderStatus === 2"
            type="primary"
            size="small"
            v-access:code="['order:update']"
            @click.stop="handleUpdateOrderStatus(row)"
          >
            订单修改
          </ghost-button>

          <!-- 取消订单 -->
          <Popconfirm
            placement="left"
            title="确认取消订单？"
            @confirm="handleCancelOrder(row)"
          >
            <ghost-button
              v-if="row.orderStatus !== 6 && row.orderStatus !== 5"
              danger
              size="small"
              @click.stop=""
              v-access:code="['order:cancel']"
            >
              取消订单
            </ghost-button>
          </Popconfirm>

          <!-- 订单退款 -->
          <Popconfirm
            placement="left"
            title="确认对订单进行退款？"
            @confirm="handleOrderRefund(row)"
          >
            <ghost-button
              v-if="
                row.orderStatus === 2 ||
                row.orderStatus === 3 ||
                row.orderStatus === 4
              "
              danger
              size="small"
              @click.stop=""
              v-access:code="['order:refund']"
            >
              订单退款
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <StatusDrawer @reload="tableApi.query()" />
  </Page>
</template>
